<template>
  <div class="container-big">
    <div style="padding-bottom: 436px;" class="container">
      <banner />
      <div class="from-box">
        <div v-if="formJson.length!=0" class="from-tit cenLeft">
          <img src="https://gw.alicdn.com/tfs/TB1vpgTHcbpK1RjSZFyXXX_qFXa-200-200.png">
          该页面内容将作为您入场的身份核验凭证，请仔细核对，准确填写真实信息
        </div>
        <div class="card-head">
          <div class="card-head-bar" />
          <div class="card-head-con cenBet">
            <div>{{activityTicketName}} </div>
          </div>
        </div>
        <div v-if="formJson.length!=0" style="padding: 0px 16px;" class="from ">
          <div v-for="(item,index) of formJson " :key="index" style="padding: 0px;position: relative;" class="from-item">
            <inputText v-if="item.componentName=='stringTem'" :this-componen="item" />
            <moreSelectPicker v-if="item.componentName=='moreSelectTem'" :this-componen="item" />
            <!-- <div @click="getAuthCode()" v-if="item.attribute.filedCode=='uTel'" class="getCode-box cenCen">
              <div class="getCode">{{authCodeTime>=60?'获取验证码':`${authCodeTime}s`}}</div>
            </div> -->
          </div>
        </div>
      </div>
      <div v-if="agreeList.length!=0" class="agree-box">
        <span @click="ifAgree=!ifAgree" class="agree-check cenCen">
          <img v-if="!ifAgree" src="https://img.alicdn.com/tfs/TB1gLM9Q7voK1RjSZFwXXciCFXa-200-200.png" />
          <img v-else src="https://img.alicdn.com/tfs/TB1fLM9Q7voK1RjSZFwXXciCFXa-200-200.png" />
        </span>
        <span @click="ifAgree=!ifAgree" style="color: #fff;" class="readAndAgree">我已仔细阅读并同意</span>
        <span>
          <br>
          <br />
          <a target="_blank" class="readAndAgree" style="   font-weight: bold;text-decoration: underline;" v-if="item.typeId==1" @click="openPage(item.agreementId)" ref="javascript:void(0);" v-for="(item,index) of agreeList" :key="index" :style="[{color:$store.state.themeColor}]">《{{item.title}}》</a>
        </span>
      </div>
    </div>
    <div class="screen-fixed-box cenCen">
      <div v-if="formJson.length!=0" @click="submit()" class="from-saveBtn from-saveBtn-ifAgree cenCen">
        确定
      </div>
    </div>
    <getCode @submitFrom="submitFrom" ref="getCode" :authCodeTime="authCodeTime" @closeshowGetCode="closeshowGetCode" @getAuthCode="getAuthCode" v-if="showGetCode" :title="activityTicketName">

    </getCode>
  </div>
</template>
<script>
// 表单组件部分
import inputText from "@/router/infoEntry/assembly/inputText"; //input type为text 组件
import moreSelectPicker from "@/router/infoEntry/assembly/moreSelectPicker";
import buyTicketService from "@/api/buyTicketService.js";

import banner from "./../orderEnter/banner/banner";
import { idcardReg } from "./../reg/idCard";
import { getParams } from "./../../utils/decodeURIComponent.js";
import service from "@/api/invoice";
import getCode from "./getCode.vue"; //获取验证码手机验证
export default {
  components: { banner, inputText, moreSelectPicker, getCode },
  data() {
    return {
      showGetCode: false, //获取验证码弹框
      authCodeField: {
        attribute: {
          filedValue: "",
          filedCode: "verifiCode",
          titName: "验证码",
          placeholder: "请输入",
          maxLength: 6,
          ifCheck: true
        },
        componentName: "stringTem"
      }, //验证码字段
      ifAgree: false, //是否同意协议
      agreeList: [], //协议
      activityName: "", // 活动名称
      ticketTypeName: "", //门票
      queryForumList: [], //论坛数据
      authCodeTime: 60, //验证码时间
      urlParams: {}, //url截取的参数
      formJson: [] //报名表单
    };
  },
  computed: {
    activityTicketName() {
      return `欢迎预订${this.activityName}${this.ticketTypeName}门票`;
    }
  },
  created() {
    this.initFun();
  },
  methods: {
    closeshowGetCode() {
      this.showGetCode = false;
    },
    async initFun() {
      // 获取链接上的一些参数
      // freeRegistration?activeId=51&ticketTypeId=213&channelId=129&corpId=ding6deeb99d5d16aed435c2f4657eb6378f
      this.urlParams = await getParams([
        "activeId",
        "ticketTypeId",
        "corpId",
        "channelId"
      ]);
      if (!this.urlParams.activeId || !this.urlParams.corpId) {
        this.$toast("必要参数丢失");
        return;
      }
      this.queryForum();
      if (sessionStorage.getItem("ifAgree") === "true") {
        this.ifAgree = true;
      }
      sessionStorage.setItem("corpIdUcan", this.urlParams.corpId);
    },
    //论坛数据 查询论坛的
    async queryForum() {
      this.$store.state.loading = true;
      const { data = [] } = await service.queryForum({
        activityId: this.urlParams.activeId,
        corpId: this.urlParams.corpId
      });
      // console.log(data);
      this.queryForumList = data;
      this.$store.state.loading = false;
      this.getFromField();
    },
    // 获取表单字段
    async getFromField() {
      this.$store.state.loading = true;
      let subData = {
        activityId: this.urlParams.activeId,
        ticketTypeId: this.urlParams.ticketTypeId,
        isPay: "free"
      };
      const { data = {} } = await service.queryTempletByTicketTypeId(subData);
      this.urlParams.tempId = data.id;
      this.activityName = data.activityName;
      if (this.activityName) {
        document.title = this.activityName;
      }
      this.ticketTypeName = `(${data.ticketTypeName})`;
      this.agreeList = [];
      if (data.agreeList.length) {
        data.agreeList.map(item => {
          if (item.typeId == 1) {
            this.agreeList.push(item);
          }
        });
      }

      if (data.vnote1) {
        this.formJson = JSON.parse(data.vnote1);
        // for (let i = 0; i < this.formJson.length; i++) {
        //   if (this.formJson[i].attribute.filedCode == "uTel") {
        //     let authCodeField = JSON.parse(JSON.stringify(this.authCodeField));
        //     this.formJson.splice(i + 1, 0, authCodeField); //添加验证码字段
        //   }
        // }

        if (this.queryForumList.length != 0) {
          // 添加论坛选择组件 (如果后台创建的论坛)
          let forum = {
            componentName: "moreSelectTem",
            attribute: {
              filedValue: "",
              filedCode: "bbsId",
              titName: "论坛意向",
              placeholder: "请选择",
              ifCheck: true,
              selectList: []
            }
          };
          for (let i = 0; i < this.queryForumList.length; i++) {
            let item = this.queryForumList[i];
            if (item.orderNum < item.bbsNum) {
              forum.attribute.selectList.push({
                //          disable: true,
                // //         disableText: "论坛已满",
                name: item.bbsName,
                ifSel: false,
                activityId: item.activityId,
                bbsId: item.bbsId,
                bbsNum: item.bbsNum,
                bbsType: item.bbsType,
                corpId: item.corpId,
                orderNum: item.orderNum
              });
            }
          }
          if (forum.attribute.selectList.length) {
            this.formJson.push(JSON.parse(JSON.stringify(forum)));
          }
          // 添加论坛选择组件
        }
        this.addAreaCode();
        this.getSessionForm();
      }
      this.$store.state.loading = false;
    },
    // ，如果有缓存则赋值
    async getSessionForm() {
      if (sessionStorage.getItem("formJson")) {
        let formJson = JSON.parse(sessionStorage.getItem("formJson"));
        for (let i = 0; i < formJson.length; i++) {
          for (let j = 0; j < this.formJson.length; j++) {
            if (
              this.formJson[j].attribute.filedCode ===
              formJson[i].attribute.filedCode
            ) {
              this.formJson[j].attribute.filedValue =
                formJson[i].attribute.filedValue;
            }
          }
        }
      }
    },
    // 关于手机号uTel增加区号字段
    addAreaCode() {
      for (let i = 0; i < this.formJson.length; i++) {
        if (this.formJson[i].attribute.filedCode == "uTel") {
          this.$set(this.formJson[i].attribute, "areaCode", "86");
        }
      }
    },
    // 获取验证码
    async getAuthCode() {
      if (this.authCodeTime < 60) {
        return;
      }

      let uTel = "";
      let countryCode = "";
      // 方式一
      // for (let i = 0; i < this.formJson.length; i++) {
      //   if (this.formJson[i].attribute.filedCode == "uTel") {
      //     uTel = this.formJson[i].attribute.filedValue;
      //     countryCode = this.formJson[i].attribute.areaCode;
      //   }
      // }
      // 方式二
      uTel = this.$refs.getCode.verifiPhoneNum;
      countryCode = this.$refs.getCode.areaCode;

      if (!uTel) {
        this.$toast("手机号不能为空");
        return;
      }
      if (uTel.length != 11 || !this.checkPhone(uTel)) {
        this.$toast("请填写正确的手机号码");
        return;
      }
      this.$store.state.loading = true;
      const { success = false } = await service.getVerificationCode({
        uTel: uTel,
        countryCode: countryCode,
        activityId: this.urlParams.activeId
      }); //获取验证码接口
      this.$store.state.loading = false;
      // 如果接口成功则倒计时
      if (success) {
        this.$toast("验证码发送成功");
        this.getAuthCodeTime();
      }
    },
    // 获取验证码时间
    getAuthCodeTime() {
      this.authCodeTime--;
      if (this.authCodeTime > 0) {
        setTimeout(() => {
          this.getAuthCodeTime();
        }, 1000);
      }
      if (this.authCodeTime <= 0) {
        this.authCodeTime = 60;
      }
    },
    openPage(agreementId) {
      sessionStorage.setItem("ifAgree", this.ifAgree);
      sessionStorage.setItem("formJson", JSON.stringify(this.formJson));
      buyTicketService.lookAgreement(agreementId).then(res => {
        if (res.success) {
          window.location.href = res.result;
        }
      });
    },
    // 提交信息
    async submit() {
      if (!this.ifAgree && this.agreeList.length) {
        let text = "";
        this.agreeList.map(item => {
          text += item.title;
        });
        this.$toast(`请您务必细阅读并同意${text}`);
        return;
      }
      //填写表单的集合数据及认证是否必填项为空
      let resData = await this.checkFromItem(this.formJson);
      if (!resData) {
        return;
      }
      this.showGetCode = true;
    },
    async submitFrom() {
      let uTel = "";
      uTel = this.$refs.getCode.verifiPhoneNum;
      if (uTel.length != 11 || !this.checkPhone(uTel)) {
        this.$toast("请填写正确的手机号码");
        this.showGetCode = true;
        return;
      }
      let subData = {
        verifiPhoneNum: this.$refs.getCode.verifiPhoneNum,
        verifiCodeStr: this.$refs.getCode.verifiCodeStr,
        corpId: this.urlParams.corpId,
        activityId: this.urlParams.activeId,
        tempId: this.urlParams.tempId,
        ticketTypeId: this.urlParams.ticketTypeId,
        channelId: this.urlParams.channelId,
        bbsId: "",
        userInfo: {}
      };
      for (let i = 0; i < this.formJson.length; i++) {
        const element = this.formJson[i];
        if (element.attribute.filedCode != "bbsId") {
          subData.userInfo[element.attribute.filedCode] =
            element.attribute.filedValue || "";
        } else {
          subData.bbsId = this.getbbsId(element.attribute.filedValue); //取ID??
        }
      }
      console.log(subData);
      // return;
      this.$store.state.loading = true;
      const res = await service.signUp(subData);
      this.$store.state.loading = false;
      console.log(res);

      if (res.success) {
        let titName = "";
        if (res.data.isReview) {
          titName = "您的报名信息已提交！请耐心等待审核结果";
        } else {
          titName = "您的报名信息已提交！";
        }
        await this.$confirm(titName, {
          title: "温馨提示",
          okLabel: "知道了",
          showCancel: false
        });
        sessionStorage.removeItem("formJson");
        this.$router.push({
          path: "/mine/registerSuccess"
        });
      }
    },
    getbbsId(name) {
      for (let i = 0; i < this.queryForumList.length; i++) {
        const element = this.queryForumList[i];
        if (name == element.bbsName) {
          return element.bbsId;
        }
      }
    },
    // 验证表格里面的每一项
    checkFromItem(formList) {
      let ifCheckAll = true; //是否检查完了全部(每一个必填项信息)
      for (let i = 0; i < formList.length; i++) {
        if (
          formList[i].attribute.ifCheck &&
          !formList[i].attribute.filedValue
        ) {
          ifCheckAll = false;
          this.$toast(
            `${
              formList[i].attribute.placeholder
                ? formList[i].attribute.placeholder
                : "请填写"
            }${formList[i].attribute.titName}`
          );
          break;
        } else if (
          //验证邮箱
          formList[i].attribute.ifCheck &&
          formList[i].attribute.filedValue &&
          formList[i].attribute.filedCode == "uEmail"
        ) {
          let regu = /@/;
          let re = new RegExp(regu);
          if (!re.test(formList[i].attribute.filedValue)) {
            ifCheckAll = false;
            this.$toast("请填写正确邮箱");
            break;
          }
        } else if (
          formList[i].attribute.ifCheck &&
          formList[i].attribute.filedValue &&
          formList[i].attribute.filedCode == "uTel" &&
          !/^\d+$/.test(formList[i].attribute.filedValue)
        ) {
          ifCheckAll = false;
          this.$toast("请填写正确的手机号码");
          break;
        } else if (
          formList[i].attribute.ifCheck &&
          formList[i].attribute.filedValue &&
          formList[i].attribute.filedCode == "uIdCard" &&
          this.isChangeType &&
          !idcardReg(formList[i].attribute.filedValue)
        ) {
          this.$toast(`请填写正确${formList[i].attribute.titName}`);
          ifCheckAll = false;
          break;
        } else if (
          formList[i].attribute.ifCheck &&
          formList[i].attribute.filedValue &&
          formList[i].attribute.filedCode == "uTel" &&
          formList[i].attribute.areaCode == "86" &&
          formList[i].attribute.filedValue.length != 11
        ) {
          ifCheckAll = false;
          this.$toast("请填写正确的手机号码");
          break;
        } else if (
          formList[i].attribute.filedCode == "uTel" &&
          !formList[i].attribute.areaCode
        ) {
          ifCheckAll = false;
          this.$toast("请点击选择手机区号");
          break;
        }
      }
      return new Promise((resolve, reject) => {
        resolve(ifCheckAll);
      });
    },
    checkPhone(phone) {
      if (!/^1[3456789]\d{9}$/.test(phone)) {
        return false;
      } else {
        return true;
      }
    }
  }
};
</script>

<style >
.from-saveBtn {
  /* position: absolute;
  left: 0px;
  bottom: 0px; */
  width: 100%;
  height: 110px;
  background: #2b2d31;
  /* font-family: PingFangSC-Regular; */
  font-size: 36px;
  color: #eeeeee;
  text-align: center;
  cursor: pointer;
}

.from-saveBtn-ifAgree {
  background-image: linear-gradient(-116deg, #3cb9ff 0%, #6044d4 100%);
}
.from-saveBtn:active {
  opacity: 0.8;
}
.from-box {
  width: 100%;
  height: auto;
  padding: 0px 5%;
  margin-top: 16px;
  z-index: 2;
}
.from-tit {
  width: 100%;
  height: auto;
  text-align: left;
  /* font-family: PingFangSC-Regular; */
  font-size: 22px;
  color: #b9b9bb;
}
.from-tit > img {
  width: 26px;
  height: auto;
  margin-right: 6px;
}
.from {
  width: 100%;
  height: auto;
  min-height: 160px;
  background: rgba(0, 0, 0, 0.4);
  /* border: 1px solid rgba(93, 93, 93, 0.2); */
  /* border: 1px solid #38383b; */
  padding: 0px 0px;
  margin-top: 0px;
  /* position: absolute;
  left: 5%;
  top: 328px; */
}
.from-item {
  width: 100%;
  height: auto;
}
.from > div:last-of-type > div {
  border-bottom: none;
}
/* 组件input样式 */
.from-input-box {
  width: 100%;
  height: auto;
  min-height: 100px;
  position: relative;
  border-bottom: 1px solid rgba(151, 151, 151, 0.2);
  padding: 6px 1px;
}
.from-input-tit {
  width: auto;
  max-width: 146px;
  height: auto;
  min-height: 100px;
  /* font-family: PingFangSC-Regular; */
  font-size: 28px;
  color: #ffffff;
  text-align: left;
  padding: 1px 6px 0px 0px;
  position: relative;
}
.select-phone {
  position: absolute;
  right: -76px;
  top: 0px;
  width: auto;
  min-width: 66px;
  height: 100%;
  cursor: pointer;
  z-index: 3;
}
.from-input-tit-check {
  margin-right: 1px;
}
.checkNot {
  opacity: 0;
}
.from-input {
  position: absolute;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  padding-left: 156px;
  padding-right: 46px;
  /* font-family: PingFangSC-Regular; */
  font-size: 28px;
  color: #fff;
  text-align: left;
}
.from-input-eng {
  padding-left: 176px;
}
.from-input-right-icon {
  position: absolute;
  right: 0px;
  top: 0px;
  width: auto;
  height: 100%;
}
.from-input-right-icon > img {
  width: 36px;
  height: auto;
}
.haveSelectPhone {
  padding-left: 236px;
}
.select-phone > img {
  width: 30px;
}
.from-input {
  text-align: left;
}

.agree-box {
  width: 100%;
  height: auto;
  text-align: center;
  font-size: 24px;
  margin-top: 26px;
  color: #fff;
}
.agree-check {
  width: 35px;
  height: auto;
  display: inline-block;
  margin-right: 10px;
  cursor: pointer;
}
.agree-check > img {
  width: 100%;
  height: auto;
  margin-top: 10px;
}
.agree-box > a,
.agree-box > span {
  cursor: pointer;
}
.agree-box > a {
  text-decoration: underline;
}
.getCode-box {
  width: 152px;
  height: 100%;
  position: absolute;
  right: -30px;
  top: 0px;
  z-index: 2;
  background: rgba(0, 0, 0, 0.1);
  background: #2b2d31;
  cursor: pointer;
}
.getCode {
  font-size: 26px;
  color: #fff;
  width: 100%;
  height: auto;
  /* background: #2b2d31; */
  padding: 10px 0px;
}
</style>
<style scope>
.card-head {
  width: 100%;
  height: auto;
  padding-bottom: 13px;
  background: #282b31;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  position: relative;
  margin-top: 16px;
}
.card-head-bar {
  width: 100%;
  height: 9px;
  opacity: 0.8;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  background-image: linear-gradient(-116deg, #3cb9ff 0%, #6044d4 100%);
}
.card-head-con {
  width: 100%;
  height: auto;
  padding: 16px 20px 6px 20px;
  font-size: 26px;
  color: #ffffff;
}
.card-con {
  width: 100%;
  height: auto;
  padding: 0px 18px;
}
</style>